import React, { Component } from 'react'
import { connect } from 'dva';

class App extends Component {
  componentDidMount = () => {
    const videoElement = document.querySelector('video');
    const audioSelect = document.querySelector('select#audioSource');
    const videoSelect = document.querySelector('select#videoSource');

    function getStream() {
      if (window.stream) {
        window.stream.getTracks().forEach(function (track) {
          track.stop();
        });
      }

      var constraints = {
        audio: {
          deviceId: { exact: audioSelect.value }
        },
        video: {
          deviceId: { exact: videoSelect.value }
        }
      };

      navigator.mediaDevices.getUserMedia(constraints).
        then(gotStream).catch(handleError);
    }

    navigator.mediaDevices.enumerateDevices()
      .then(gotDevices).then(getStream).catch(handleError);

    audioSelect.onchange = getStream;
    videoSelect.onchange = getStream;

    function gotDevices(deviceInfos) {
      for (var i = 0; i !== deviceInfos.length; ++i) {
        var deviceInfo = deviceInfos[i];
        var option = document.createElement('option');
        option.value = deviceInfo.deviceId;
        if (deviceInfo.kind === 'audioinput') {
          option.text = deviceInfo.label ||
            'microphone ' + (audioSelect.length + 1);
          audioSelect.appendChild(option);
        } else if (deviceInfo.kind === 'videoinput') {
          option.text = deviceInfo.label || 'camera ' +
            (videoSelect.length + 1);
          videoSelect.appendChild(option);
        } else {
          console.log('Found one other kind of source/device: ', deviceInfo);
        }
      }
    }

    function gotStream(stream) {
      window.stream = stream; // make stream available to console
      videoElement.srcObject = stream;
    }

    function handleError(error) {
      console.error('Error: ', error);
    }
  }

  render() {
    return (
      <div>
        <div className="select">
          <label for="audioSource">Audio source: </label><select id="audioSource"></select>
        </div>

        <div className="select">
          <label for="videoSource">Video source: </label><select id="videoSource"></select>
        </div>
        <video muted autoplay></video>
      </div>
    )
  }
}

export default connect()(App);
